import sys
import time
import image
import psutil
import wx
import decimal
from Extend.NoSql import Heart
from TechnologicalProcess import ServiceMainControl
from threading import Thread

from min import MyTaskBarIcon
decimal.__version__


class LoginFrame(wx.Frame):
    def __init__(self):
        self.services = ServiceMainControl()
        size = (460, 140 + len(self.services.services_name) * 40)
        # 初始化窗口。设定窗口大小
        super().__init__(None, title='文件分发工具___by:墨妖', size=size,
                         style=wx.CLOSE_BOX | wx.MINIMIZE_BOX | wx.CAPTION)
        self.SetIcon(wx.Icon(image.Logo.getIcon()))
        self.SetMinSize(size)
        # 窗口居中
        self.Center()
        # 开启可以放置内容的空间
        self.panel = wx.Panel(self, -1)
        # 设置所有内容的字体大小
        self.panel.SetFont(font=wx.Font(10, wx.DEFAULT, wx.NORMAL, wx.NORMAL, False))
        self.row_pos = 10
        self.line_object = []
        self.start_all, self.stop_all = wx.Button(), wx.Button()
        # 设置UI
        self.myUi()
        # 绑定事件
        self.binds()
        self.min_window = MyTaskBarIcon(self)
        # self.startMoniter()

    def myUi(self):
        title = wx.StaticText(self.panel, label='文件分发工具')
        title.SetPosition(((self.GetSize()[0] - title.GetSize()[0]) / 2 - 55, self.row_pos))
        title.SetFont(font=wx.Font(22, wx.DEFAULT, wx.NORMAL, wx.BOLD, False, faceName='黑体'))
        title.SetForegroundColour('#339999')
        self.row_pos = 70
        for index in range(len(self.services.services_name)):
            self.line_object.append(LineInfo(self.panel, self.row_pos, self.services, index, self.Bind))
            self.row_pos += 33
        # 启动所有服务和停止所有服务的按钮设置
        line_pos = 60
        self.start_all = wx.Button(self.panel, label='启动所有服务', pos=(line_pos, self.row_pos))
        line_pos += 200
        self.stop_all = wx.Button(self.panel, label='停止所有服务', pos=(line_pos, self.row_pos))
        self.stop_all.SetSize((120, 40))
        self.start_all.SetSize((120, 40))
        self.start_all.SetFont(font=wx.Font(12, wx.DEFAULT, wx.NORMAL, wx.BOLD, False, faceName='微软雅黑'))
        self.stop_all.SetFont(font=wx.Font(12, wx.DEFAULT, wx.NORMAL, wx.BOLD, False, faceName='微软雅黑'))
        self.start_all.SetBackgroundColour('#43CD80')
        self.stop_all.SetBackgroundColour('#EEAD0E')
        # self.start_all.SetForegroundColour('white')
        # self.stop_all.SetForegroundColour('white')
        self.start_all.SetFocus()
        # 最小化到托盘区
        line_pos += 70
        self.to_min = wx.Button(self.panel, label='最小化')
        x = self.GetSize()[0] - self.to_min.GetSize()[0] - 30
        y = self.GetSize()[1] - self.to_min.GetSize()[1] * 3
        self.to_min.SetPosition((x, y))

    def binds(self):
        self.Bind(wx.EVT_BUTTON, self.startAll, self.start_all)
        self.Bind(wx.EVT_BUTTON, self.stopAll, self.stop_all)
        self.Bind(wx.EVT_BUTTON, self.windowMin, self.to_min)
        self.Bind(wx.EVT_CLOSE, self.OnClose)

    def startAll(self, event):
        # self.services.startAllServer()
        for index in range(len(self.services.services)):
            if self.line_object[index].getLineStat() != 2:
                self.services.startSever(index)
                t = Thread(target=self.services.startSever, args=(index,), daemon=True)
                t.start()

    def windowMin(self, event):
        self.Show(False)

    def OnClose(self, event):
        self.min_window.Destroy()
        self.Destroy()

    def stopAll(self, event):
        for index in range(len(self.services.services)):
            if self.line_object[index].getLineStat() != 2:
                t = Thread(target=self.services.stopSever, args=(index,), daemon=True)
                t.start()
                # self.services.stopSever(index)
            if self.line_object[index].getLineStat() == 1:
                self.line_object[index].setLineStat(2)
        # t = Thread(target=self.services.stopAllServer)
        # t.start()
        # self.services.stopAllServer()

    # def startMoniter(self):
    #     t = Thread(target=self.getServicesStatus, daemon=True)
    #     t.start()
    #
    # def getServicesStatus(self):
    #     while True:
    #         stops = self.services.allServerStatus()
    #         print(stops)
    #         for x in range(len(self.line_object)):
    #             line_stat = self.line_object[x].getLineStat()
    #             if x in stops:
    #                 if line_stat is True:
    #                     self.line_object[x].setLineStat(False)
    #             else:
    #                 if line_stat is False:
    #                     self.line_object[x].setLineStat(True)
    #         time.sleep(1)


# 每一行的信息
class LineInfo:
    def __init__(self, panel, pos, service: ServiceMainControl, index: int, bind):
        self.panel = panel
        self.__stat = 0
        self.row_pos = pos
        self.line_pos = 20
        self.stat_label = wx.StaticText()
        self.start_button = wx.Button()
        self.stop_button = wx.Button()
        self.drawLine(service.services_name[index])
        self.service = service
        self.me_index = index
        self.Bind = bind
        self.binds()
        self.startMoniter()

    def drawLine(self, name):
        name_label = wx.StaticText(self.panel, pos=(self.line_pos, self.row_pos), label=name)
        self.line_pos += name_label.GetSize()[0]
        self.stat_label = wx.StaticText(self.panel, pos=(self.line_pos, self.row_pos))
        self.stat_label.SetSize(100, (self.stat_label.GetSize()[1]))
        self.row_pos -= 4
        self.line_pos = 240
        self.start_button = wx.Button(self.panel, label='启动服务', pos=(self.line_pos, self.row_pos))
        self.line_pos += self.start_button.GetSize()[0] + 30
        self.stop_button = wx.Button(self.panel, label='停止服务', pos=(self.line_pos, self.row_pos))
        self.setLineStat(0)

    def setLineStat(self, stat: int):
        self.__stat = stat
        if stat == 1:
            self.stat_label.SetForegroundColour("#33cccc")
            self.stat_label.SetLabel("●正在运行")
            self.start_button.Enable(False)
            self.stop_button.Enable(True)
        elif stat == 2:
            self.stat_label.SetForegroundColour("#FF8C00")
            self.stat_label.SetLabel("▲正在停止...")
            self.start_button.Enable(False)
            self.stop_button.Enable(False)
        else:
            self.stat_label.SetForegroundColour("#ff0066")
            self.stat_label.SetLabel('○已停止')
            self.stop_button.Enable(False)
            self.start_button.Enable(True)

    def getLineStat(self):
        return self.__stat

    def binds(self):
        self.Bind(wx.EVT_BUTTON, self.startEnv, self.start_button)
        self.Bind(wx.EVT_BUTTON, self.stopEnv, self.stop_button)

    def startEnv(self, env):
        self.setLineStat(1)
        t = Thread(target=self.service.startSever, args=(self.me_index,), daemon=True)
        t.start()
        # self.service.startSever(self.me_index)

    def stopEnv(self, env):
        self.setLineStat(2)
        t = Thread(target=self.service.stopSever, args=(self.me_index,), daemon=True)
        t.start()
        # self.service.stopSever(self.me_index)

    def startMoniter(self):
        t = Thread(target=self.getServicesStatus, daemon=True)
        t.start()

    def getServicesStatus(self):
        while True:
            try:
                proc = self.service.process[self.me_index]
                service = self.service.services[self.me_index]
                pid = Heart.getPid(service.__class__.__name__)
                if type(proc) is not int and proc.is_alive() and psutil.pid_exists(pid):
                    if self.__stat == 0:
                        self.setLineStat(1)
                else:
                    raise SystemError
            except Exception as err:
                Heart.setMeStat(service.__class__.__name__, False)
                if self.__stat != 0:
                    self.setLineStat(0)
            #
            #
            # stops = self.services.allServerStatus()
            # print(stops)
            # for x in range(len(self.line_object)):
            #     line_stat = self.line_object[x].getLineStat()
            #     if x in stops:
            #         if line_stat is True:
            #             self.line_object[x].setLineStat(False)
            #     else:
            #         if line_stat is False:
            #             self.line_object[x].setLineStat(True)
            time.sleep(1)


if __name__ == '__main__':
    app = wx.App()
    main_window = LoginFrame()
    try:
        if sys.argv[1].lower() == 'startall':
            main_window.services.startAllServer()
        elif sys.argv[1].lower() == 'start':
            main_window.services.startSever(int(sys.argv[2]))
    except:
        pass
    main_window.Show()
    # 启动主循环
    app.MainLoop()
